#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-01-16 16:38:40

import threading
import random
import time
import sys


def light():
    '''
    set 之后为绿灯状态
    clear 之后为红灯状态
    '''
    if not event.isSet():
        event.set()  # wait就不阻塞 #绿灯状态
    count = 0
    while True:
        if count < 10:
            print('\033[42;1m--green light on---\033[0m')
        elif count < 13:
            print('\033[43;1m--yellow light on---\033[0m')
        elif count < 20:
            if event.isSet():
                event.clear()  # 清楚set装填，打开红灯状态
            print('\033[41;1m--red light on---\033[0m')
        else:
            count = 0
            event.set()  # 打开绿灯
        time.sleep(1)
        count += 1


def car(n):
    '''
    检查 event 状态判断红、绿灯
    '''
    while True:
        time.sleep(random.randrange(10))
        if event.isSet():
            print("car [%s] is running.." % n)
        else:
            print("car [%s] is waiting for the red light.." % n)


if __name__ == '__main__':
    try:
        event = threading.Event()
        # 启动红绿灯线程
        Ligit = threading.Thread(target=light)
        Ligit.start()
        # 启动车线程
        for i in xrange(3):
            t = threading.Thread(target=car, args=(i,))
            t.start()
    except KeyboardInterrupt:
        sys.exit(2)
